<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>用户标签</h3>
    </div>
    <el-row>
      <!-- <el-col :xs="24" :sm="12" :lg="6">
        <el-input placeholder="部门名称"></el-input>
      </el-col> -->
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <!-- <el-button v-ripple @click="refresh">刷新</el-button> -->
        <el-button @click="showDialog('add')" v-ripple>新增标签</el-button>
      </el-col>
    </el-row>

    <art-table
      :data="tableData"
      :loading="tableLoading"
      :currentPage="pageNum"
      :pageSize="pageSize"
      :total="pageTotal"
      @current-change="currentChange"
      @size-change="sizeChange"
    >
      <template #default>
        <el-table-column label="ID" prop="id" width="55" align="center" />
        <el-table-column label="排序" prop="sort" align="center" />
        <el-table-column label="标签名称" prop="name" align="center" />
        <el-table-column label="创建时间：" prop="createTime" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <!-- <el-table-column fixed="right" label="操作" width="100px">
          <template #default="scope">
            <el-row>
              <button-more :list="[
                { key: 'edit', label: '编辑' },
                { key: 'delete', label: '删除' }
              ]" @click="buttonMoreClick($event, scope.row)" />
            </el-row>
          </template>
        </el-table-column> -->
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增标签' : '编辑标签'"
      width="30%"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" :rows="3" />
        </el-form-item>
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { useMenuStore } from '@/store/modules/menu'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { formatMenuTitle } from '@/router/utils/utils'
  import { userLabelList, AddUserLabel, DelUserLabel } from '@/api/userStudentsApi'

  const dialogVisible = ref(false)
  const permissionDialog = ref(false)
  const menuList = computed(() => useMenuStore().getMenuList)

  const formRef = ref<FormInstance>()

  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入标签名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    sort: [{ required: true, message: '请输入正确排序', trigger: 'blur' }]
  })

  const form = reactive({
    id: '',
    name: '',
    sort: '1',
    remark: ''
  })

  const tableData = ref([])

  const dialogType = ref('add')
  const tableLoading = ref(false)
  const pageNum = ref(1)
  const pageSize = ref(10)
  const pageTotal = ref(0)
  async function getData() {
    try {
      tableLoading.value = true
      const { code, data } = await userLabelList({
        pageNum: pageNum.value,
        pageSize: pageSize.value
      })
      if (code === '00000' && data) {
        tableData.value = data.list
        pageTotal.value = data.total

        console.log(tableData.value, 'tableData.value')
      }
    } catch (e) {
    } finally {
      tableLoading.value = false
    }
  }

  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    if (type === 'edit' && row) {
      form.id = row.id
      form.name = row.name
      form.sort = row.sort
      form.remark = row.remark
    } else {
      form.id = ''
      form.name = ''
      form.remark = ''
    }
  }

  const buttonMoreClick = (row: any) => {
    // if (item.key === 'permission') {
    //   showPermissionDialog()
    // } else if (item.key === 'edit') {
    showDialog('edit', row)
    // } else if (item.key === 'delete') {
    //   deleteRole(row.id)
    // }
  }

  const showPermissionDialog = () => {
    permissionDialog.value = true
  }

  const defaultProps = {
    children: 'children',
    label: (data: any) => formatMenuTitle(data.meta?.title) || ''
  }

  const deleteRole = (id: number) => {
    ElMessageBox.confirm('确定删除该标签吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      const res = await DelUserLabel(id)
      if (res.code === '00000') {
        ElMessage.success('删除成功')
        getData()
      }
    })
  }

  const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate(async (valid) => {
      if (!valid) return

      const isAdd = dialogType.value === 'add'
      const message = isAdd ? '新增成功' : '修改成功'
      const params: any = {
        name: form.name,
        sort: form.sort,
        remark: form.remark
      }
      if (!isAdd) {
        params.id = form.id
      }

      try {
        const res = await AddUserLabel(params)
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      } catch (error) {
        // 可根据需要添加错误处理
        console.error('操作失败', error)
      }
    })
  }

  const formatDate = (date: string) => {
    return new Date(date)
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
      .replace(/\//g, '-')
  }
  const currentChange = (val: number) => {
    pageNum.value = val
    getData()
  }

  const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData()
  }
  const refresh = () => {
    getData()
  }

  onMounted(() => {
    getData()
  })
</script>

<style lang="scss" scoped>
  .page-content {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }
  }
</style>
